package com.example.blog.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.config.SmmsDao;
import com.example.blog.entity.Photo;
import com.example.blog.entity.Result;
import com.example.blog.mapper.PhotoMapper;
import com.example.blog.utils.UserHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PhotoService extends ServiceImpl<PhotoMapper, Photo> {

    @Resource
    private SmmsDao smmsDao;

    public Result upload(MultipartFile file, String info, String classify) {
        final Result result = smmsDao.upload(file);
        if(result.getCode()==400) {
            return result;
        }
        Photo photo = new Photo();
        // 如果照片已存在, 则给一份到当前用户
        if(result.getMsg() != null && result.getMsg().equals("image_repeated")){
            final List<Photo> photoList = query()
                    .eq("url", result.getData())
                    .list();
            if(!photoList.isEmpty()){
                photo = photoList.get(0);
            }
        }
        else {
            photo = (Photo) result.getData();
        }
        photo.setPhotoInfo(info);
        photo.setUserId(UserHolder.getUser().getUserId());
        photo.setClassify(classify);

        final int res = baseMapper.insert(photo);
        return Result.ok(photo);
    }

    public Result delete(String photoId) {
        final List<Photo> photoList = query()
                .eq("photo_id", photoId)
                .eq("user_id", UserHolder.getUser().getUserId())
                .list();
        if(photoList.isEmpty()){
            return Result.fail("该用户无此图片");
        }
        final Photo photo = photoList.get(0);
        final int res = baseMapper.deleteById(photo.getPhotoId());
        // 如果是最后一张 则删除云存储
        final int photoNum = query()
                .eq("url", photo.getUrl())
                .list()
                .size();
        if(photoNum == 0){
            return smmsDao.delete(photo.getPhotoHash());
        }
        return Result.ok("File delete success.");
    }

    public Result getClassPhoto(String classify) {
        final List<Photo> photoList = query()
                .eq("user_id", UserHolder.getUser().getUserId())
                .eq("classify", classify)
                .list();
        return Result.ok(photoList);
    }

    public Result getClassify() {
        List<Photo> photoList = query()
                .eq("user_id", UserHolder.getUser().getUserId())
                .list();
        Set<String> classifies = photoList.stream()
                .map(Photo::getClassify)
                .collect(Collectors.toSet());

        return Result.ok(classifies);
    }
}
